package com.fjec.devops.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fjec.common.okhttp.OkHttp;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.Base64Util;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.util.NumberUtil;
import com.fjec.common.wx.WxAccessTokenHelper;
import com.fjec.devops.entity.InfoCooperator;
import com.fjec.devops.mapper.InfoCooperatorMapper;
import com.fjec.devops.schedule.DevopsSchedule;
import com.fjec.devops.schedule.handler.AccessTokenHandler;
import com.fjec.devops.service.IInfoCooperatorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.JsonObject;
import com.mysql.cj.jdbc.Blob;
import okhttp3.Response;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialBlob;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import static com.fjec.common.util.Base64Util.encode;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-10-26
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class InfoCooperatorServiceImpl extends ServiceImpl<InfoCooperatorMapper, InfoCooperator> implements IInfoCooperatorService {

    @Resource
    private InfoCooperatorMapper mapper;

    @Autowired
    private OkHttp okHttp;

    @Autowired
    private WxAccessTokenHelper wxAccessTokenHelper;

    @Override
    public boolean saveOrUpdateCooperator(InfoCooperator infoCooperator) {
        if (infoCooperator.getId() == null) {
            Integer maxCode = mapper.getMaxCode();
            if (maxCode == null || maxCode == 0) {
                maxCode = 100001;
            } else {
                maxCode += 1;
            }
            maxCode = Math.toIntExact(NumberUtil.giveUpNum(maxCode, 4));
            infoCooperator.setCode(maxCode);
            infoCooperator.setCreateTime(DateUtil.nowLdt());
            this.save(infoCooperator);
            // 获取合伙人推广码
            String smallAppCodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
            String access_token = wxAccessTokenHelper.getWxCenterAccessToken();
            smallAppCodeUrl += access_token;
            Map<String, Object> reqBody = new HashMap();
            reqBody.put("path", "?cooperatorId=" + infoCooperator.getId());
            byte[] bytes = okHttp.postJsonBytes(smallAppCodeUrl, JsonUtil.toJson(reqBody));

            String result = new String(bytes);
            if (JSONUtil.isJson(result)) {
                Map<String, Object> errResult = JsonUtil.jsonToMap(result);
                Integer errCode = MapUtils.getInteger(errResult, "errcode");
                if (errCode != null) {
                    access_token = wxAccessTokenHelper.refreshWxCenterAccessToken();
                } else {
                    access_token = wxAccessTokenHelper.getWxCenterAccessToken();
                }
                smallAppCodeUrl += access_token;
                bytes = okHttp.postJsonBytes(smallAppCodeUrl, JsonUtil.toJson(reqBody));
            }

            infoCooperator.setSmallAppCode(Base64Util.encode(bytes));
        }

        this.updateById(infoCooperator);
        return true;
    }

    @Override
    public void downloadBarcode(Long id, HttpServletResponse response) throws Exception {
        InfoCooperator entity = mapper.selectById(id);
        if (entity != null) {
            // 获取合伙人推广码
            String smallAppCodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=";
            String access_token = wxAccessTokenHelper.getWxCenterAccessToken();
            smallAppCodeUrl += access_token;
            Map<String, Object> reqBody = new HashMap();
            reqBody.put("path", "?cooperatorId=" + entity.getId());
            byte[] bytes = okHttp.postJsonBytes(smallAppCodeUrl, JsonUtil.toJson(reqBody));
            StringBuilder sb = new StringBuilder();
            sb.append(entity.getName())
                    .append(entity.getPhone())
                    .append(".png");
            String fileName = URLEncoder.encode(sb.toString(), "UTF-8");
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + bytes.length);
            response.setContentType("application/octet-stream");
            OutputStream out = response.getOutputStream();
            out.write(bytes, 0, bytes.length);
            out.flush();
        }
    }
}
